/**
 * wap 全局 js文件
 * @authors supmain (mtingfeng@gmail.com)
 * @date    2014-12-01 11:53:04
 * @for *.html
 * @version $1.0$
 */
var TBS = TBS || {} ,
	$window = $( window ) ;
TBS.homepage = {
	userinfor: {} ,
	init: function(){
		var that = this;
		that.treeWatering();
    },
    treeWatering: function(){
    	var $ctmain = $(".ctmain") ,
    		$water = $("#watering") ,
    		$tree = $("#tree") ,
    		$guide = $( "#gameguide" ) ,
    		$flow = $("#capacity_num") ,
    		$txt = $( "#capacity p em" ) ,
            $share = $("#sns .share") ,
            $mcover = $("#mcover") ,
    		otree = new Tree( $tree ).init() ,
    		owater = new Water( otree , $water ).init() ,
    		oguide = new Guide( $guide ) ,
    		oflow = new Flow( $flow , $txt ) ,
    		flag = true ,                   // 是否计时
            watering = false ,              // 是否正在浇水动画中
    		startime = null ,
    		swipecount = 0 ,
    		timer = null ;

    	$ctmain.on("swipeDown",function( ev ){
            if( checkAuthority()  ){
                swipecount++;                 // 纪录总次数
                flag && startSwipeCount();    // 10s 计时
                watering ? '' : swipeSpeed(); // 游戏实时速度
                oguide.hide();                // 隐藏游戏玩法指导
            };
    		ev.preventDefault();
    	}).on("touchend",function(){
            watering ? oflow.stopLoseWater : oflow.autoLoseWater();
    	});
        // 检测是否可以游戏
        function checkAuthority(){
            var count = user.count ,
                couldCount = user.couldCount ,
                resume = couldCount - count ;
            if( resume == 0 ){
                TBS.dialog.tip("您今日的浇水次数已达上限，请明天再来，或者分享获取更多游戏机会。");
                return false;
            };
            return true;
        };
    	// 开始游戏计数
    	function startSwipeCount(){
            var sec = 0 ;
    		flag = false;
    		startime = new Date().getTime() / 1000 ;
    		timer = setInterval(function(){
                if( sec == 2 ){
                    clearInterval(timer);
                    timer = null;

                    var num = oflow.getFlow() ;
                    if( num == 0 ){
                        TBS.dialog.tip("此次浇水量为0升，再接再厉噢！") ;
                        resetSetting();         // 游戏结束，重置
                    }else{
                        oflow.stopLoseWater();  // 水量自动减少停止
                        watering = true;
                        owater.prepareWater();  // 开始浇水动画
                        setTimeout(function(){
                            TBS.dialog.confirm("恭喜您，浇水"+ oflow.getFlow() +"升，小树苗正在快快长大，快来分享朋友圈获取更多浇水次数吧！",function(){
                                $mcover.show();
                            },undefined,function(){
                                TBS.dialog.close();
                                resetSetting();  // 游戏结束，重置
                            });
                        },3000);
                    };
                    updateWaterData( num );      // 更新个人游戏数据
                };
                sec++;
    		},1000);
    	};
        function updateWaterData( water ){
            user.count = user.count + 1 ;
            // ajax 发送完成一次浇水动作
            /*$.ajax({
              type: 'GET',
              url: '/projects',
              data: { studentid: user.studentid , count: user.count , water: user.water  },
              dataType: 'json',
              context: $('body'),
              success: function(data){

              },
              error: function(xhr, type){
                TBS.dialog.tip("网络错误");
              }
            });*/

        };
    	// 显示滑动速率
    	function swipeSpeed(){
    		var endtime = new Date().getTime() / 1000 ;
    			interval = endtime - startime ;
    		if( interval < 1 ) interval = 1 ;	// 防止时间过小数字过大。
    		var	speed = swipecount / interval ;
    		if( isFinite( speed ) ){
    			// 速度 扩大10呗 ， 最快50，计算比例。最后乘以50L的水
    			speed = parseInt( speed * 10 ) ;
    			//var height = speed / 50 * 118 + 20 ;
    			oflow.setCapacity( speed ) ;
    		};
    	};
        // 重置游戏
        function resetSetting(){
            flag = true ;
            swipecount = 0 ;
            watering = false ;              // 标记浇水动画结束
            owater.stopWatering() ;         // 停止浇水动画
            oflow.setCapacity( 0 ) ;        // 水量为0
            oguide.show() ;                 // 提示游戏玩法
        };
    	// 屏幕大小改变
    	$window.on("resize",function(){
    		owater.resizePosition() ;
    	});
        // 分享
        $share.on("click",function(){
            $mcover.show();
        });
    }
};

$(function(){
   TBS.homepage.init();
});
/**
 * [Water 水壶对象]
 * @param {[树对象]} otree  [小树]
 * @param {[zepto对象]} $water [水壶]
 */
function Water( otree , $water ){
	this.otree = otree ;
	this.water = $water;
	this.img_waterdrop = 'images/tmp_water.gif';
	return this;
};
// 准备静态资源
Water.prototype.init = function(){
	for( var src in this ){
		if( $.type(this[src]) == "string" && this[src].indexOf("images/") >= 0 ){
			var img = new Image() ;
			img.onload = function(){ };
    		img.onerror = function(){ };
    		img.src = this[src] ;
		};
	};
	return this;
};
// 准备浇水
Water.prototype.prepareWater = function(){
	var	that = this ,
		$water = this.water ,
		otree = this.otree ,
		pn = this.calculatePosition() ,
		top = pn.top ,
		right = pn.right ;
	$water.on("webkitTransitionEnd transitionend",function( ev ){
		that.startWatering();
		otree.getBigger() ;
		$(this).addClass('watering').off();
	}).css({"top":top,"right":right});
	return this;
};
// 开始浇水
Water.prototype.startWatering = function(){
	var	$water = this.water ;
		$water.find("#waterdrop").length == 0 ? $water.append("<div id='waterdrop'><img class='drop' src='" + this.img_waterdrop + "'/></div>") : null ;
	return this;
};
// 停止浇水
Water.prototype.stopWatering = function(){
	var	$water = this.water ,
        otree = this.otree ;
	$water.removeClass('watering').css({"top":110,"right":20}).find("#waterdrop .drop").removeClass('drop');
    otree.stopBigger("treeBigger");
};
// 计算位置
Water.prototype.calculatePosition = function(){
	var	that = this ,
		$water = this.water ,
		$tree = this.otree.tree ,
		wateroffset = $water.offset() ;
		pn_water = {
			w: wateroffset.width ,
			h: wateroffset.height ,
			t: wateroffset.top ,
			l: wateroffset.left
		};
	var treeoffset = $tree.offset() ,
		pn_tree = {
			w: treeoffset.width ,
			h: treeoffset.height ,
			t: treeoffset.top ,
			l: treeoffset.left
		};
	var top = pn_tree.t - pn_water.h ,
		right = pn_tree.w / 2 + pn_tree.l - pn_water.w / 2 ;
	top += 40 ;
	right -= 80 ;
	return { top: top , right: right };
};
// 调整位置
Water.prototype.resizePosition = function(){
	var pn = this.calculatePosition();
	this.water.css({"top":pn.top,"right":pn.right});
};
/**
 * [Tree 树对象]
 * @param {[zepto对象]} $tree [小树苗]
 */
function Tree( $tree ){
	this.tree = $tree ;
};
Tree.prototype.init = function(){
	return this;
};
Tree.prototype.getBigger = function(){
	var $tree = this.tree ;
	$tree.addClass('treeBigger');
};
Tree.prototype.stopBigger = function(){
    var $tree = this.tree ;
    $tree.removeClass('treeBigger');
};
/**
 * [ 游戏玩法指引 ]
 * @param {[jquery]} $guide [指引jquery对象]
 */
function Guide( $guide ){
	this.$guide = $guide ;
}
Guide.prototype.hide = function(){
	this.$guide.hide();
};
Guide.prototype.show = function(){
	this.$guide.show();
};
/**
 * [ 水壶蓄水 ]
 * @param {[zepto]} $flow [水量高度]
 * @param {[zepto]} $txt  [水量大小]
 */
function Flow( $flow , $txt ){
	var _this = this;
	this.$flow = $flow ;
	this.$txt = $txt ;
	this.timer = null ;
};
Flow.prototype.setCapacity = function( speed ){
	var $flow = this.$flow ,
		$txt = this.$txt ;
		height = speed / 50 * 118 + 20 ;
	$txt.text( speed ) ;
	if( height >=20 && height <=138 ){
		$flow.height( height ) ;
	};
};
Flow.prototype.autoLoseWater = function(){
	var _this = this;
	if( this.timer ){
		clearInterval( this.timer );
		this.timer = null;
	};
	this.timer = setInterval(function(){
		var num = parseInt( _this.$txt.text() ) ;
		if( num == 0 ){ clearInterval( _this.timer ); return; }
		num--;
		_this.setCapacity( num );
	},300);
};
Flow.prototype.stopLoseWater = function(){
	if( this.timer ){
		clearInterval( this.timer );
		this.timer = null;
	};
};
Flow.prototype.getFlow = function(){
	return this.$txt.text();
};